package com.sk.weichat.ui.circle;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Animatable;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.SingleLayoutHelper;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.cjt2325.cameralibrary.util.ScreenUtils;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;
import com.nineoldandroids.animation.ObjectAnimator;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sk.weichat.R;
import com.sk.weichat.adapter.DynamicHeadAdapter;
import com.sk.weichat.bean.AddAttentionResult;
import com.sk.weichat.bean.AttentionUser;
import com.sk.weichat.bean.DynamicBean;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.User;
import com.sk.weichat.bean.circle.PublicMessage;
import com.sk.weichat.bean.message.ChatMessage;
import com.sk.weichat.bean.message.NewFriendMessage;
import com.sk.weichat.bean.message.XmppMessage;
import com.sk.weichat.broadcast.CardcastUiUpdateUtil;
import com.sk.weichat.db.dao.ChatMessageDao;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.NewFriendDao;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.helper.FriendHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.base.CoreManager;
import com.sk.weichat.ui.message.search.SearchUserAndRoomActivity;
import com.sk.weichat.util.FrescoUtils;
import com.sk.weichat.util.ScreenUtil;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.util.ViewPiexlUtil;
import com.sk.weichat.util.keyboard.KeyboardHeightObserver;
import com.sk.weichat.util.keyboard.KeyboardHeightProvider;
import com.sk.weichat.view.SelectionFrame;
import com.sk.weichat.xmpp.ListenerManager;
import com.sk.weichat.xmpp.listener.ChatMessageListener;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.callback.JsonCallback;
import com.xuan.xuanhttplibrary.okhttp.callback.ListCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ArrayResult;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;
import com.xuan.xuanhttplibrary.okhttp.result.Result;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import okhttp3.Call;


import static com.sk.weichat.bean.DynamicBean.DynamicBean_Key;
import static com.xuan.xuanhttplibrary.okhttp.result.Result.CODE_SUCCESS;

/**
 * @author lzs
 * @date 2019/10/28
 * Email:343067508@qq.com
 **/
public class DynamicDetailsActivity extends BaseActivity implements KeyboardHeightObserver {
    private static final int duration = 200;
    private DelegateAdapter delegateAdapter;

    private LinkedList<DelegateAdapter.Adapter> adapterList = new LinkedList<>();

    private SmartRefreshLayout refreshLayout;
    DynamicBean dynamicBean;

    //监听键盘弹起收回状态
    KeyboardHeightProvider keyboardHeightProvider;

    //
    View layoutCommentInput;

    TextView tvTime;
    //顶部昵称
    TextView tvName;
    //顶部头像
    SimpleDraweeView ivAvatarTop;
    //底部输入框头像
    SimpleDraweeView ivAvatar;

    TextView tvAttention;

    int actionBarHeight; //顶部标题栏高度

    public static final void startDynamicDetailsActivity(Context context, DynamicBean dynamicBean) {
        Intent intent = new Intent(context, DynamicDetailsActivity.class);
        intent.putExtra(DynamicBean_Key, (Parcelable) dynamicBean);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic_details);
        ConstraintLayout actionBar = findViewById(R.id.actionBar);
        actionBar.setPadding(0, ScreenUtil.getStatusHeight(mContext), 0, 0);
        ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) actionBar.getLayoutParams();
        lp.height += ScreenUtil.getStatusHeight(mContext);
        actionBar.setLayoutParams(lp);
        dynamicBean = getIntent() == null ? null : getIntent().getParcelableExtra(DynamicBean_Key);
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        refreshLayout = findViewById(R.id.refresh_layout);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

            }
        });
        VirtualLayoutManager layoutManager = new VirtualLayoutManager(this);

        RecyclerView recyclerView = findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(layoutManager);
        delegateAdapter = new DelegateAdapter(layoutManager, false);
        recyclerView.setAdapter(delegateAdapter);
        if (dynamicBean != null) {
            getDetails();
        }

        ivAvatar = findViewById(R.id.iv_avatar);
        FrescoUtils.loadImage(ivAvatar, AvatarHelper.getAvatarUrl(dynamicBean.getUserId(), true));
        ivAvatarTop = findViewById(R.id.iv_avatar_top);
        FrescoUtils.loadImage(ivAvatarTop, AvatarHelper.getAvatarUrl(dynamicBean.getUserId(), true));

        tvAttention = findViewById(R.id.tv_attention);

        tvName = findViewById(R.id.tv_name);
        tvName.setText(dynamicBean.getNickName());
        //顶部时间
        tvTime = findViewById(R.id.tv_time);
        tvTime.setText(TimeUtils.getFriendlyTimeDesc(mContext, dynamicBean.getTime()));
        //
        layoutCommentInput = findViewById(R.id.layout_input_comment);
        keyboardHeightProvider = new KeyboardHeightProvider(this);
        keyboardHeightProvider.setKeyboardHeightObserver(this);
        recyclerView.post(new Runnable() {
            @Override
            public void run() {
                actionBarHeight = actionBar.getHeight();
                keyboardHeightProvider.start();
            }
        });


        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int totalY = 0;

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                totalY += dy;
                if (totalY >= actionBarHeight) {
                    //显示顶部的头像和标题栏
                    fadeIn(tvName, duration);
                    fadeIn(tvAttention, duration);
                    fadeIn(tvTime, duration);
                    fadeIn(ivAvatarTop, duration);
                } else {
                    //
                    fadeOut(tvName, duration);
                    fadeOut(tvAttention, duration);
                    fadeOut(tvTime, duration);
                    fadeOut(ivAvatarTop, duration);
                }
            }
        });
    }


    private void fadeIn(View view, int duration) {
        ObjectAnimator animator = ObjectAnimator.ofFloat(view, "alpha", 0f, 1f);
        animator.setDuration(duration);
        animator.start();
    }

    private void fadeOut(View view, int duration) {
        ObjectAnimator animator = ObjectAnimator.ofFloat(view, "alpha", 1f, 0f);
        animator.setDuration(duration);
        animator.start();
    }

    @Override
    public void onKeyboardHeightChanged(int height, int orientation) {
        //Log.e("lzs", "height:" + height);
        if (height > 0) {
            //弹起
            ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) layoutCommentInput.getLayoutParams();
            lp.bottomMargin = height;
            layoutCommentInput.setLayoutParams(lp);
        } else {
            //收回
            ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) layoutCommentInput.getLayoutParams();
            lp.bottomMargin = 0;
            layoutCommentInput.setLayoutParams(lp);
        }
    }

    /**
     * 获取动态详情
     */
    private void getDetails() {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        //动态id
        params.put("messageId", dynamicBean.getMessageId());
//        if (messageId != null) {
//            params.put("messageId", messageId);
//        }
        HttpUtils.get().url(coreManager.getConfig().MSG_GET)
                .params(params)
                .build()
                .execute(new BaseCallback<DynamicBean>(DynamicBean.class) {
                    @Override
                    public void onResponse(ObjectResult<DynamicBean> result) {
                        if (result.getResultCode() == CODE_SUCCESS) {
                            DynamicBean dynamicBean = result.getData();
                            adapterList.add(new DynamicHeadAdapter(dynamicBean, mContext));
                            delegateAdapter.setAdapters(adapterList);
                            delegateAdapter.notifyDataSetChanged();
                            setAttentionStatus(dynamicBean.getUserId(), dynamicBean.getNickName(), dynamicBean.getIfAttention());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        refreshLayout.finishLoadMore();
                    }
                });
    }

    private void setAttentionStatus(String toUserId, String nickName, int isAttention) {
        if (isAttention == 0) {
            tvAttention.setText("+ 关注");
            tvAttention.setTextAppearance(mContext, R.style.text_attention_nomal);

            tvAttention.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });

        } else if (isAttention != -1) {
            //不是黑名单用户，
            tvAttention.setText("已关注");
            tvAttention.setTextAppearance(mContext, R.style.text_attention_select);
            tvAttention.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showCancelAttentionDialog(new SelectionFrame.OnSelectionFrameClickListener() {
                        @Override
                        public void cancelClick() {

                        }

                        @Override
                        public void confirmClick() {
                            if (isAttention == 1) {
                                //已关注，不是好友
                                cancelAttention(toUserId, nickName, false);
                            } else if (isAttention == 2) {
                                cancelAttention(toUserId, nickName, true);
                            }
                        }
                    });
                }
            });
        }
    }

    // 点击加好友就调用这个方法，
    private void doAddAttention(String toUserid) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("toUserId", toUserid);

        HttpUtils.get().url(coreManager.getConfig().FRIENDS_ATTENTION_ADD)
                .params(params)
                .build()
                .execute(new BaseCallback<AddAttentionResult>(AddAttentionResult.class) {

                    @Override
                    public void onResponse(ObjectResult<AddAttentionResult> result) {
                        if (result.getResultCode() == 1 && result.getData() != null) {

                            // FriendHelper.updateFriendRelationship(coreManager.getSelf().getUserId(), user);
                            // Friend friend = FriendDao.getInstance().getFriend(mLoginUserId, user.getUserId());
                            if (result.getData().getType() == 1 || result.getData().getType() == 3) {
                                // 需要验证就发送打招呼的消息，
//                                if (user.getFriends() == null
//                                        || (user.getFriends().getReplyStatus() != Friend.STATUS_REPLAY_BOTH
//                                        && user.getFriends().getIsBeenBlack() != 1
//                                        && result.getData().getIsFollowed() == 0)) {// 未回复并且未关注过的发送打招呼消息
//
//                                    doSayHello(toUserid, coreManager.getSelf().getUserId(),coreManager.getSelf().getNickName() + "关注了你");
//                                }
//                                if (user.getFriends().getIsBeenBlack() == 1) {//被拉黑的关注时状态还是被拉黑
//                                    FriendDao.getInstance().updateBeBlack(coreManager.getSelf().getUserId(), toUserid, 1);
//                                    FriendDao.getInstance().updateFriendStatus(coreManager.getSelf().getUserId(),toUserid, Friend.STATUS_ATTENTION);
//                                } else {
//                                    FriendDao.getInstance().updateBeBlack(coreManager.getSelf().getUserId(), toUserid, 0);
//                                    FriendDao.getInstance().updateFriendStatus(coreManager.getSelf().getUserId(), toUserid, Friend.STATUS_ATTENTION);
//                                }
//                                user.getFriends().setStatus(Friend.STATUS_ATTENTION);
//                            } else if (result.getData().getType() == 2 || result.getData().getType() == 4) {// 已经是好友了
//                                if (user.getFriends() == null ||
//                                        (user.getFriends().getReplyStatus() != Friend.STATUS_REPLAY_BOTH
//                                                && user.getFriends().getIsBeenBlack() != 0
//                                                && result.getData().getIsFollowed() == 0)) {// 未回复并且未关注过的发送打招呼消息
//
//                                    doSayHello(user, coreManager.getSelf().getNickName() + "关注了你，你们已经是好友，可以互发语音");
//                                }
//                                FriendDao.getInstance().updateFriendStatus(coreManager.getSelf().getUserId(), user.getUserId(), Friend.STATUS_FRIEND);
//                                user.getFriends().setStatus(Friend.STATUS_FRIEND);
                            } else if (result.getData().getType() == 5) {
                                ToastUtil.showToast(DynamicDetailsActivity.this, R.string.add_attention_failed);
                            }
                        } else {
                            Toast.makeText(DynamicDetailsActivity.this, result.getResultMsg() + "", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        Toast.makeText(DynamicDetailsActivity.this, R.string.tip_hello_failed, Toast.LENGTH_SHORT).show();
                        ToastUtil.showErrorNet(DynamicDetailsActivity.this);
                    }
                });
    }

    // 打招呼
    private void doSayHello(String fromUserID, String toUserID, String text) {
        ChatMessage sayMessage = new ChatMessage();
        sayMessage.setFromUserId(fromUserID);
        sayMessage.setFromUserName(coreManager.getSelf().getNickName());
        sayMessage.setToUserId(toUserID);
        sayMessage.setContent(text);
        sayMessage.setType(XmppMessage.TYPE_TEXT); //文本类型
        sayMessage.setMsgType(ChatMessage.TYPE_HELLO);
        sayMessage.setMySend(true);
        sayMessage.setMessageState(ChatMessageListener.MESSAGE_SEND_SUCCESS);
        sayMessage.setPacketId(UUID.randomUUID().toString().replaceAll("-", ""));
        sayMessage.setTimeSend(TimeUtils.sk_time_current_time());

        // 这里最终调用smack的发送消息，
        coreManager.sendChatMessage(toUserID, sayMessage);
        ChatMessageDao.getInstance().saveNewSingleChatMessage(fromUserID, toUserID, sayMessage);
    }

    private void cancelAttention(String toUserId, String nickName, boolean isFriend) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("toUserId", toUserId);

        HttpUtils.get().url(coreManager.getConfig().CANEL_ATTENTION)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {

                    @Override
                    public void onResponse(ObjectResult<Void> result) {

                        if (result.getResultCode() == 1) {
                            findViewById(R.id.layout_more_attention).setVisibility(View.GONE);

                            //好友取消关注需要在关系通知提醒
                            if (isFriend) {
                                ChatMessage removeChatMessage = new ChatMessage();
                                removeChatMessage.setContent("你取关了" + nickName + "，解除好友关系");
                                removeChatMessage.setTimeSend(TimeUtils.sk_time_current_time());
                                FriendDao.getInstance().updateLastChatMessage(coreManager.getSelf().getUserId(), Friend.ID_NEW_FRIEND_MESSAGE, removeChatMessage);

                                NewFriendMessage message = NewFriendMessage.createLocalMessage(
                                        coreManager.getSelf(), XmppMessage.TYPE_CANCEL_ATTENTION, null, toUserId, nickName);

                                NewFriendDao.getInstance().createOrUpdateNewFriend(message);
                                NewFriendDao.getInstance().changeNewFriendState(message.getUserId(), Friend.STATUS_27);
                                ListenerManager.getInstance().notifyNewFriend(coreManager.getSelf().getUserId(), message, true);
                                FriendDao.getInstance().updateFriendStatus(coreManager.getSelf().getUserId(), message.getUserId(), Friend.STATUS_BE_ATTENTION);

                                CardcastUiUpdateUtil.broadcastUpdateUi(mContext);
                            }
                        } else {
                            ToastUtil.showToast(DynamicDetailsActivity.this, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {

                    }
                });
    }

    private void showCancelAttentionDialog(SelectionFrame.OnSelectionFrameClickListener listener) {
        SelectionFrame mSF = new SelectionFrame(this);
        mSF.setSomething(getString(R.string.dialog_title), getString(R.string.sure_cancel_attention), listener);
        mSF.show();
    }

    @Override
    protected void onDestroy() {
        keyboardHeightProvider.close();
        super.onDestroy();
    }


}
